package nix.bs.web.servlet;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Properties;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import nix.bs.domain.Cart;
import nix.bs.domain.CartItem;
import nix.bs.domain.Order;
import nix.bs.domain.OrderItem;
import nix.bs.domain.User;
import nix.bs.service.OrderService;
import nix.commons.CommonUtils;
import nix.servlet.BaseServlet;

public class OrderServlet extends BaseServlet {

	private OrderService orderService = new OrderService();

	/**
	 * 生成订单
	 */
	public String add(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		Cart cart = (Cart) request.getSession().getAttribute("cart");
		// 使用Cart创建Order
		Order order = new Order();
		order.setOid(CommonUtils.uuid());
		order.setOrdertime(new Date());
		order.setTotal(cart.getTotal());
		order.setState(1);
		order.setOwner((User) request.getSession().getAttribute("session_user"));

		List<OrderItem> orderItemList = new ArrayList<OrderItem>();
		for (CartItem cartItem : cart.getCartItems()) {
			OrderItem orderItem = new OrderItem();
			orderItem.setIid(CommonUtils.uuid());
			orderItem.setCount(cartItem.getCount());
			orderItem.setSubtotal(cartItem.getSubTotal());
			orderItem.setOrder(order);
			orderItem.setBook(cartItem.getBook());
			orderItemList.add(orderItem);
		}
		order.setOrderItemList(orderItemList);
		// 清空购物车
		cart.clear();
		orderService.add(order);
		request.setAttribute("order", order);

		return "f:/bs/jsps/order/desc.jsp";
	}

	/**
	 * 我的订单
	 */
	public String myOrders(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		User user = (User) request.getSession().getAttribute("session_user");
		List<Order> orderList = orderService.myOrders(user.getUid());
		request.setAttribute("orderList", orderList);
		return "f:/bs/jsps/order/list.jsp";
	}

	/**
	 * 按oid查询订单
	 */
	public String load(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		String oid = request.getParameter("oid");
		Order order = orderService.load(oid);
		request.setAttribute("order", order);
		return "f:/bs/jsps/order/desc.jsp";
	}

	/**
	 * 确认收货
	 */
	public String confirm(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		String oid = request.getParameter("oid");
		try {
			orderService.confirm(oid);
			return myOrders(request, response);
		} catch (Exception e) {
			request.setAttribute("msg", e.getMessage());
			return "f:/bs/jsps/msg.jsp";
		}
	}

	/**
	 * 支付（去银行）
	 */
	public String pay(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		Properties props = new Properties();
		props.load(this.getClass().getClassLoader()
				.getResourceAsStream("merchantInfo.properties"));
		// 13参数
		String p0_Cmd = "Buy";
		String p1_MerId = "10001126856";
		String p2_Order = request.getParameter("oid");
		String p3_Amt = "0.01";// request.getParameter("total");
		String p4_Cur = "CNY";
		String p5_Pid = "";
		String p6_Pcat = "";
		String p7_Pdesc = "";
		String p8_Url = props.getProperty("p8_Url");
		String p9_SAF = "";
		String pa_MP = "";
		String pd_FrpId = request.getParameter("pd_FrpId");
		String pr_NeedResponse = "1";
		// Hmac
		String keyValue = props.getProperty("keyValue");
		String hmac = PaymentUtil.buildHmac(p0_Cmd, p1_MerId, p2_Order, p3_Amt,
				p4_Cur, p5_Pid, p6_Pcat, p7_Pdesc, p8_Url, p9_SAF, pa_MP,
				pd_FrpId, pr_NeedResponse, keyValue);
		// 支付请求Url（13参数+Hmac）
		StringBuilder url = new StringBuilder(props.getProperty("url"));
		url.append("?p0_Cmd=").append(p0_Cmd);
		url.append("&p1_MerId=").append(p1_MerId);
		url.append("&p2_Order=").append(p2_Order);
		url.append("&p3_Amt=").append(p3_Amt);
		url.append("&p4_Cur=").append(p4_Cur);
		url.append("&p5_Pid=").append(p5_Pid);
		url.append("&p6_Pcat=").append(p6_Pcat);
		url.append("&p7_Pdesc=").append(p7_Pdesc);
		url.append("&p8_Url=").append(p8_Url);
		url.append("&p9_SAF=").append(p9_SAF);
		url.append("&pa_MP=").append(pa_MP);
		url.append("&pd_FrpId=").append(pd_FrpId);
		url.append("&pr_NeedResponse=").append(pr_NeedResponse);
		url.append("&hmac=").append(hmac);

		response.sendRedirect(url.toString());
		return null;
	}

	/**
	 * 支付（回调）
	 */
	public String back(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		Properties props = new Properties();
		props.load(this.getClass().getClassLoader()
				.getResourceAsStream("merchantInfo.properties"));
		// 接收11+1参数
		String p1_MerId = request.getParameter("p1_MerId");
		String r0_Cmd = request.getParameter("r0_Cmd");
		String r1_Code = request.getParameter("r1_Code");
		String r2_TrxId = request.getParameter("r2_TrxId");
		String r3_Amt = request.getParameter("r3_Amt");
		String r4_Cur = request.getParameter("r4_Cur");
		String r5_Pid = request.getParameter("r5_Pid");
		String r6_Order = request.getParameter("r6_Order");
		String r7_Uid = request.getParameter("r7_Uid");
		String r8_MP = request.getParameter("r8_MP");
		String r9_BType = request.getParameter("r9_BType");
		String hmac = request.getParameter("hmac");
		// 校验
		String keyValue = props.getProperty("keyValue");
		boolean bool = PaymentUtil.verifyCallback(hmac, p1_MerId, r0_Cmd,
				r1_Code, r2_TrxId, r3_Amt, r4_Cur, r5_Pid, r6_Order, r7_Uid,
				r8_MP, r9_BType, keyValue);
		if (!bool) {
			request.setAttribute("msg", "非法请求！");
			return "f:/bs/jsps/msg.jsp";
		}
		// 支付
		orderService.pay(r6_Order);
		// 回调方式：1 重定向；2 点对点；
		if (r9_BType.equals("2")) {
			response.getWriter().print("success");
		}
		request.setAttribute("msg", "支付成功，尽快为您发货，请耐心等待！");
		return "f:/bs/jsps/msg.jsp";
	}
}
